package com.aliengen.thingple.thingple.service;

import android.app.Application;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.aliengen.thingple.thingple.handler.CMCHandler;
import com.aliengen.thingple.thingple.preferences.PreferencesUtil;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class HandsetApplication extends Application {

    Intent intent;
    public ThingpleService mService;
    public boolean bBind = false;
    CMCHandler handler = null;

    public CMCHandler getHandler()
    {
        return this.handler;
    }

    public void setHandler(CMCHandler handler) {
        this.handler = handler;
        if(mService != null && mService.device != null)
        {
            mService.device.setHandler(handler);
        }
    }

    public ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("----Service Disconnected----");
            mService.device.onDisconnect();
            bBind = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("----Service Connected!----");
            ThingpleService.ThingpleBinder binder = (ThingpleService.ThingpleBinder)service;
            mService = binder.GetService();

            if(handler == null)
            {
                System.out.println("Error! Handler not set!");
                return;
            }

            mService.SetBinder(getApplicationContext(), handler);
            mService.device.onConnect();
            bBind = true;
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

        Context ctx = getApplicationContext();
        PreferencesUtil.init(ctx);

        initService();
    }

    public void initService()
    {
        System.out.println("Init service...");
        intent = new Intent(this, ThingpleService.class);
        startService(intent);
        try{
            bindService(intent, conn, Service.BIND_AUTO_CREATE);
        }catch(Exception e){e.printStackTrace();}
    }

    public void killService()
    {
        System.out.println("Killing service...");
        unbindService(conn);
        stopService(intent);
    }

    public void restartService()
    {
        System.out.println("Restarting service...");
        killService();
        initService();
    }
}
